<%
/**
 * wizard refresh flow action
 *
 * When a page (/ partial) is rendered, any DOM event handlers need to be
 * (re-)attached. The af:ajaxButton, af:ajaxSubmitJs and af:redirect tags
 * supports calling a JavaScript after the page has been rendered by passing
 * the 'afterSuccess' argument.
 *
 * Example:	af:redirect afterSuccess="onPage();"
 * 		af:redirect afterSuccess="console.log('redirecting...');"
 *
 * Generally one would expect this code to add jQuery event handlers to
 * DOM objects in the rendered page (/ partial).
 *
 * @author	Jeroen Wesbeek <work@osx.eu>
 * @package AjaxFlow
 */
%>
<script type="text/javascript">
		
		function showAge(data,textStatus){
			$('#age').val(data);
			}
		function showAnomaliaBancariaType(){
			
			var clickAct=""+$('input[name=toPageOne]').attr('onclick');
			clickAct=clickAct.replace("success:function(data,textStatus){jQuery('#interviewPage').html(data);hideSpinner();onPage();", "success:function(data,textStatus){hideSpinner();onPage();");
			$('input[name=toPageOne]').attr('onclick',clickAct);
			$('input[name=toPageOne]').click();
			${remoteFunction(
									controller:'Interview',
									params: [interviewId: interview?.id],
									action:'renderAnomaliaBancaria',
									update:'render_anomaliaBancaria')}
			}

		function showCodicePratica(data,textStatus){
			$('#codPratica').val(data);
			}

		function validStep(){
			
			$.validator.addMethod('italiandate', function (value) {
			       return /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/.test(value) || /^$/.test(value);;
			}, 'Inserire una data valida (gg/mm/aaaa)');		
			$.validator.addMethod('lettersspaceonly', function (value) {
			       return /^[a-zA-Zàèéìòù\'\.\s]*$/.test(value);
			}, 'Inserisci solo lettere o spazi');		
			$.validator.addMethod('numericOnly', function (value) {
			       return /^[0-9]+$/.test(value);
			}, 'Inserisci solo numeri validi (0-9)');
			$.validator.addMethod('numericOnlyNull', function (value) {
			       return /^[0-9]+$/.test(value) || /^$/.test(value);
			}, 'Solo Valori numerici (0-9)');
			$.validator.addMethod('CF_PIVA', function (value) {
			       return /^[a-z]{6}\d{2}[abcdehlmprst]\d{2}[a-z]\d{3}[a-z]/i.test(value) || /^[0-9]{11}$/.test(value) || /^$/.test(value);
			}, 'Inserire un codice fiscale valido o una partita iva valida');
			$.validator.addMethod('EURO', function (value) {
				 return /^(0|[1-9]\d*)(\.\d{1,2})?$/.test(value) || /^$/.test(value);
			}, 'Solo Valori numerici,inserire il punto al posto della virgola, max 2 valori dopo il punto');
			$.validator.addMethod('PIVA', function (value) {
			       return /^[0-9]{11}$/.test(value) || /^$/.test(value);
			}, 'Inserire una partita iva valida');
			$.validator.addMethod('CF', function (value) {
			       return /^[a-z]{6}\d{2}[abcdehlmprst]\d{2}[a-z]\d{3}[a-z]/i.test(value) || /^$/.test(value);
			}, 'Inserire un codice fiscale valido');
			
			var $validator = $("#interview").validate({
			rules: {
				//page 1
			    email: {
			        required: false,
			        email: true
			    },
			    name: {
					required: true,
			        rangelength:[2,50],
			        lettersspaceonly: true  
			    },
			    surname: {
			    	required: true,
			        rangelength:[2,50],
			        lettersspaceonly: true
			    },
			    born:{
			    	required: false,
			    	italiandate:true,
				},
				cf_piva:{
					required: true,
					CF_PIVA:true,
				        "remote":
		                {
		                  url: '${createLink(controller:'customer',action:'check_customer_unique_cf_piva')}',
		                  type: "post",
		                  data:
		                  {
		                      interview_id: function()
		                      {
		                          return ${interview?.id};
		                      }
		                  }
		                }
				},   
			    age: {
			        required: false,
			        numericOnlyNull:true
			    },
			    born_province: {
			        required: false
			    },
			    residence_province: {
			        required: false
			    },
			    residence_municipality: {
				    required: false
				},
			    residence_cap: {
				    required: false
				},
			    residence_address: {
				    required: false
				},
			    phone: {
			        required: false,
			        minlength: 6,
			        numericOnlyNull:true
			    },
			    mobile:{
			    	required: false,
			    	numericOnlyNull:true
				},

			//page 1 tab 2
				pgName: {
					<% if(name==null || surname==null || cf_piva==null){ %>
					   required:true,
					<% } %>
			        rangelength:[2,50]
			    },
				pgCf:{
					required: false,
					CF:true,
					"remote":
	                {
	                  url: '${createLink(controller:'customer',action:'check_pg_unique_cf')}',
	                  type: "post",
	                  data:
	                  {
	                      interview_id: function()
	                      {
	                          return ${interview?.id};
	                      }
	                  }
	                }
				},   
				pgPiva:{
					<% if(name==null || surname==null || cf_piva==null){ %>
					   required:true,
					<% } %>
					PIVA:true,
					"remote":
	                {
	                  url: '${createLink(controller:'customer',action:'check_pg_unique_piva')}',
	                  type: "post",
	                  data:
	                  {
	                      interview_id: function()
	                      {
	                          return ${interview?.id};
	                      }
	                  }
	                }
				},   
			    pgResidence_province: {
			        required: false
			    },
			    pgResidence_municipality: {
				    required: false
				},
				pgResidence_cap: {
				    required: false
				},
				pgResidence_address: {
				    required: false
				},
				pgPhone: {
			        required: false,
			        minlength: 6,
			        numericOnlyNull:true
			    },
				pgMobile:{
			    	required: false
				},
				pgEmail: {
			        required: false,
			        email: true
			    },
	
			//page 2
				redditoNettoAnnuo:{
					required: false,
				},
				mensilita:{
					required: false,
			        numericOnlyNull:true
				},
				contractType:{
					required: false,
				},
				impiegoType:{
					required: false,
				},
				attivoLastYear:{
					required: false,
					
				},
				ricaviLordiLastYear:{
					required: false,
					
				},
				debitiLastYear:{
					required: false,
					
				},
				attivoSecondLastYear:{
					required: false,
					
				},
				ricaviLordiSecondLastYear:{
					required: false,
					
				},
				debitiSecondLastYear:{
					required: false,
					
				},
				attivoThirdLastYear:{
					required: false,
					
				},
				ricaviLordiThirdLastYear:{
					required: false,
					
				},
				debitiThirdLastYear:{
					required: false,
					
				},
				activityType:{
					required: false,
				},
				rendita:{
					required: false,
				},
				rendita_importo:{
					required: false,
					
				},
				
			//page 3
			    familiesNumber: {
			        required: false,
			        numericOnlyNull:true
			    },
			    job:{
					required: false,
				},
			    ran:{
					required: false,
					
				},
			//page 4
			
			    tipologyBene:{
					required: false,
				},	
			    valoreStimaMerc:{
					required: false,
					
				},
			    note:{
					required: false,
				},
				immobileType:{
					required: false,
				},	
				metriQuadri:{
					required: false,
					numericOnlyNull: true
				},	
				immobil_province:{
					required: false,
				},	
				immobil_municipality:{
					required: false,
				},
				immobil_cap: {
				    required: false
				},
				immobil_address: {
				    required: false
				},	
				rataMensileMutuo:{
					required: false,
					
				},
				valoreMutuo:{
					required: false,
					
				},
				stimaMercatoAttuale:{
					required: false,
					
				},
						
			//page 5
				debitType:{
					required: false,
				},	
				credit:{
					required: false,
				},	
				capitalRes:{
					required: false,
					
				},
				rate:{
					required: false,
					
				},
				partner:{
					required: false,
				},	
				notes:{
					required: false,
				},	
				cessioniDeleghe:{
					required: false,
				},
				cPI:{
					required: false,
				},  
			    note:{
				   	required: false,
				}
				
			},			    
			    messages: {
			      	name:{
				      	required:"Bisogna spedificare il nome del cliente",
				      	nowhitespace:"Non puoi inserire spazi",
				      	rangelength:"Il nome deve essere almeno di {0} caratteri e al massimo di {1} caratteri",
				      	lettersonly:"Non puoi inserire numeri nel nome"
				    }, 
			      	surname:{
				      	required:"Bisogna spedificare il cognome del cliente",
				      	nowhitespace:"Non puoi inserire spazi",
				      	rangelength:"Il cognome deve essere almeno di {0} caratteri e al massimo di {1} caratteri",
				      	lettersonly:"Non puoi inserire numeri nel cognome"
				    },
				   	born:{
						required:"Inserire la data di nascita del cliente"
					},
				 	cf_piva:{
					  	required:"Inserire il CF o la P.IVA del cliente",
					  	remote:"Esiste gi&agrave; un cliente con CF / PIVA uguale"
					},
					pgCf:{
						remote:"Esiste gi&agrave; una posizione giuridica con CF uguale"
					},
					 pgPiva:{
						 required:"Inserire la P.IVA della Persona Giuridica",
						remote:"Esiste gi&agrave; una persona giuridica con P.IVA uguale"
					},
					pgName:{
				      	rangelength:"Il nome deve essere almeno di {0} caratteri e al massimo di {1} caratteri",
    					 required:"Inserire la Denominazione della Persona Giuridica"
					},					
				},
			    
			    highlight: function (element) {
			      $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
			    },
			    unhighlight: function (element) {
			      $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
			    },
			    errorElement: 'span',
			    errorClass: 'help-block',
			    errorPlacement: function (error, element) {
			      if (element.parent('.input-group').length) {
			        error.insertAfter(element.parent());
			      } else {
			        error.insertAfter(element);
			      }
			    },
			    invalidHandler: function(form, validator) {
					$("#validity_label").html('<i class="fa-fw fa fa-warning"></i>Ci sono '+validator.numberOfInvalids()+' infomazion'+(validator.numberOfInvalids()>1?'i':'e')+' mancant'+(validator.numberOfInvalids()>1?'i':'e'));
					$("#validity_label").show();
				}
			  });
			var $valid = $("#interview").valid();
			if (!$valid) {
		        $validator.focusInvalid();
		        throw new Error('step is invalid');
			}
		}

		  function reset_born_municipality(){
				$("#born_municipality").select2("val","");
			}

		  //CLIENTE STEP
          function formatProvince(state){
                return state.text
          }

        function onPage() {
            	
        		
                if (console) {
                        console.log('calling onPage() which can be used to attach generic javascript handlers to DOM elements of a rendered page / partial');
                }
                
                pageSetUp();
                
                $('#validity_label').hide();
             // fuelux wizard
  			  var wizard = $('.wizard').wizard();
  			  
  			  wizard.on('finished', function (e, data) {
  			    //$("#fuelux-wizard").submit();
  			    //console.log("submitted!");
  			    $.smallBox({
  			      title: "Congratulations! Your form was submitted",
  			      content: "<i class='fa fa-clock-o'></i> <i>1 seconds ago...</i>",
  			      color: "#5F895F",
  			      iconSmall: "fa fa-check bounce animated",
  			      timeout: 4000
  			    });			    
  			  });
  			  
             
                
                $('#born_province').select2({
                   allowClear: true,
                   minimumInputLength: 1,
                   formatNoMatches:'Nessuna corripondenza',
                   formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
                   formatSearching:'Stiamo cercando le province...' ,
                   
                   ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                       url: "/province/list",
                       dataType: 'json',
                       quietMillis: 250,
                       data: function (term, page) {
                           return {
                               index: term, // search term
                           };
                       },
                       results: function (data, page) { // parse the results into the format expected by Select2.
                           // since we are using custom formatting functions we do not need to alter the remote JSON data
                           return { results: data.results };
                       },                       
                       cache: true
                   },   
                });
                
                $('#born_province').on("change", function(e) {
                    ${remoteFunction(asynchronous: true,
			            				action:'get_municipality',
										controller:'province',
										params:'\'pr=\' + this.value',
										update:'born_municipality',
										onSuccess:'reset_born_municipality()'									
										)} 
                 //cambiando rimettere a null il comune   
                 });

              
				
                $('#born_municipality').select2({
                	allowClear: false,
                    formatNoMatches:'Nessuna corripondenza',
                    formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
                    formatSearching:'Stiamo cercando i comuni...' ,
                 });
                
                $('#residence_province').select2({
                    allowClear: true,
                    minimumInputLength: 1,
                    formatNoMatches:'Nessuna corripondenza',
                    formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
                    formatSearching:'Stiamo cercando le province...' ,
                    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                        url: "/province/list",
                        dataType: 'json',
                        quietMillis: 250,
                        data: function (term, page) {
                            return {
                                index: term, // search term
                            };
                        },
                        results: function (data, page) { // parse the results into the format expected by Select2.
                            // since we are using custom formatting functions we do not need to alter the remote JSON data
                            return { results: data.results };
                        },
                        cache: true
                    },   
                 });
                
                $('#residence_province').on("change", function(e) {
                    ${remoteFunction(asynchronous: true,
			            				action:'get_municipality',
										controller:'province',
										params:'\'pr=\' + this.value',
										update:'residence_municipality',
										onSuccess:'reset_residence_municipality();reset_residence_cap()'	
										)} 
                  //cambiando rimettere a null il comune e cap  
                 });

                function reset_residence_municipality(){
					$("#residence_municipality").select2("val","");
				}
				                
                $('#residence_municipality').select2({
                	allowClear: false,
                    formatNoMatches:'Nessuna corripondenza',
                    formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
                    formatSearching:'Stiamo cercando i comuni...' ,
                 });
                
                $('#residence_municipality').on("change", function(e) {
                    ${remoteFunction(asynchronous: true,
            				action:'get_cap',
							controller:'province',
							params:'\'mun=\' + this.value',
							onSuccess:'$("#residence_cap").val(data)',
							)}        
        		});

                function reset_residence_cap(){
					$("#residence_cap").val("");
				}


                
                $('#pgResidence_province').select2({
                    allowClear: true,
                    minimumInputLength: 1,
                    formatNoMatches:'Nessuna corripondenza',
                    formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
                    formatSearching:'Stiamo cercando le province...' ,
                    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                        url: "/province/list",
                        dataType: 'json',
                        quietMillis: 250,
                        data: function (term, page) {
                            return {
                                index: term, // search term
                            };
                        },
                        results: function (data, page) { // parse the results into the format expected by Select2.
                            // since we are using custom formatting functions we do not need to alter the remote JSON data
                            return { results: data.results };
                        },
                        cache: true
                    },   
                 });
                
                $('#pgResidence_province').on("change", function(e) {
                    ${remoteFunction(asynchronous: true,
			            				action:'get_municipality',
										controller:'province',
										params:'\'pr=\' + this.value',
										update:'pgResidence_municipality',
										onSuccess:'reset_pgResidence_municipality();reset_pgResidence_cap()'	
										)} 
                  //cambiando rimettere a null il comune e cap  
                 });

                function reset_pgResidence_municipality(){
					$("#pgResidence_municipality").select2("val","");
				}
				                
                $('#pgResidence_municipality').select2({
                	allowClear: false,
                    formatNoMatches:'Nessuna corripondenza',
                    formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
                    formatSearching:'Stiamo cercando i comuni...' ,
                 });
                
                $('#pgResidence_municipality').on("change", function(e) {
                    ${remoteFunction(asynchronous: true,
            				action:'get_cap',
							controller:'province',
							params:'\'mun=\' + this.value',
							onSuccess:'$("#pgResidence_cap").val(data)',
							)}        
        		});

                function reset_pgResidence_cap(){
					$("#residence_cap").val("");
				}
				  


                
                $('#abode_province').select2({
                    allowClear: true,
                    minimumInputLength: 1,
                    formatNoMatches:'Nessuna corripondenza',
                    formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
                    formatSearching:'Stiamo cercando le province...' ,
                    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                        url: "/province/list",
                        dataType: 'json',
                        quietMillis: 250,
                        data: function (term, page) {
                            return {
                                index: term, // search term
                            };
                        },
                        results: function (data, page) { // parse the results into the format expected by Select2.
                            // since we are using custom formatting functions we do not need to alter the remote JSON data
                            return { results: data.results };
                        },
                        cache: true
                    },   
                 });
                
                $('#abode_province').on("change", function(e) {
                    ${remoteFunction(asynchronous: true,
			            				action:'get_municipality',
										controller:'province',
										params:'\'pr=\' + this.value',
										update:'abode_municipality',
										onSuccess:'reset_abode_municipality();reset_abode_cap()'	
										)}                                    
                });
                
                function reset_abode_municipality(){
					$("#abode_municipality").select2("val","");
				}

                
                $('#abode_municipality').select2({
                    allowClear: false,
                    formatNoMatches:'Nessuna corripondenza',
                    formatInputTooShort:'Inserire almeno un carattere per iniziare la ricerca',
                    formatSearching:'Stiamo cercando i comuni...' ,                       
                 });
                
                $('#abode_municipality').on("change", function(e) {
                    ${remoteFunction(asynchronous: true,
            				action:'get_cap',
							controller:'province',
							params:'\'mun=\' + this.value',
							onSuccess:'$("#abode_cap").val(data)'
							)}        
        		});              

                function reset_abode_cap(){
					$("#abode_cap").val("");
				}
				                
               var bornDP =$("#born_datepicker").datepicker({ 
				              	autoclose:"true", 
		    					format:"dd/mm/yyyy"
		        			});
		        bornDP.on('changeDate', function(e){
		        	var date = $(this).datepicker('getDate');
	
					var dateVal = $.datepicker.formatDate('dd/mm/yy', date);
					$('#born').val(dateVal);
					$('#born').change();
		        });
		        

				var rm=remappingBean();    	
				readOnly();
				toUpperCase();
				currencyFormatter();
        				
    		} 
    	function toUpperCase(){
    			$(".select2-hidden-accessible").addClass('text-uppercase');
               	$(':input').addClass('text-uppercase');
        		$(':radio,:checkbox').addClass('text-uppercase');
        		$('.select2-chosen').addClass('text-uppercase');
        		$( ":button" ).addClass('text-uppercase');
        		$('select').addClass('text-uppercase');
    	}	
		function readOnly(){
			<exdutility:isReadOnly test="true">
				$(".select2-hidden-accessible").hide();
               	$(':input').attr('readonly','readonly');
        		$(':radio,:checkbox').click(function(){
        		    return false;
        		});
        		$('.select2-chosen').click(function(){
        		    return false;
        		});
        		$( ":button" ).addClass('disabled');
        		$('select').prop('disabled', 'disabled');
        		if($( "input[name='pdfCreate']")){
        			$( "input[name='pdfCreate']").removeAttr('readonly');
        			$( "input[name='pdfCreate']").removeClass('disabled');
        		}
        		$( ".btn-open-folder" ).removeClass('disabled');
        	</exdutility:isReadOnly>	
		}      
		function currencyFormatter(){
		$('.currency').priceFormat({
		    prefix: '',
		    thousandsSeparator: '.',
		    centsSeparator: ',',
		    
		});
        } 
   function uploadAj(){

	
	 var input = document.getElementById("exampleInputFile1");
	
	var interId = $('#interviewId').val();
	var comments = $('#comments').val();
	var folder = $('#documentType').val();
	var data = new FormData();
	data.append("interviewId", interId);
	data.append("comments", comments); 
	data.append("folderId", folder); 

	
	data.append("file",input.files[0]);

	spinPage(true);
	pleaseWait();

	  $.ajax({
		  xhr: function()
		  {
		    var xhr = new window.XMLHttpRequest();
		    //Upload progress
		    xhr.upload.addEventListener("progress", function(evt){
		      if (evt.lengthComputable) {
			      
		        var percentComplete = evt.loaded / evt.total;
		        //Do something with upload progress
		        var cento = percentComplete*100;
<%--			        $('#myprogress').css('width', percentComplete+'%').attr('aria-valuenow', percentComplete);--%>
		        $('#myprogress').attr('aria-valuenow', cento);
		        $('#myprogress').css('width', cento + '%');

					$("#myprogress").html(cento.toFixed(0)+"%");
			   }
		    }, false);
		    //Download progress
		    xhr.addEventListener("progress", function(evt){
		      if (evt.lengthComputable) {
		        var percentComplete = evt.loaded / evt.total;
		        //Do something with download progress
		        $('.progress-bar').css('width', percentComplete+'%').attr('aria-valuenow', percentComplete);
				$("myprogress").html(percentComplete);
			   }
		    }, false);
		    return xhr;
		  },
		  	
	        url: "${createLink(action:'uploadFromAj')}",
	        type: 'POST',
	        data: data,
	        cache: false,
	        
	        processData: false, // Don't process the files
	        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
	        success: function(data, textStatus, jqXHR)
	        {
	            if(typeof data.error === 'undefined')
	            {
	                // Success so call function to process the form
	                successUpload(data);
	                show_files(folder,"date");
	                resetafterUp();
	            }
	            else
	            {
	                // Handle errors here
	               
	                console.log('ERRORS: ' + data.error);
	            }
	        },
	        error: function(jqXHR, textStatus, errorThrown)
	        {
	            // Handle errors here
	            console.log('ERRORS: ' + textStatus);
	            
	            failureUpload(jqXHR,textStatus,errorThrown)
	            spinPage(false);
	            resetafterUp();
	            // STOP LOADING SPINNER
	        },
	        complete: function()
	        {
				spinPage(false);
				 resetafterUp();
				
	            // STOP LOADING SPINNER
	        }
	    });

}
        
 
</script>

<div id ="uploadpp">
		
	<g:render template="/_common/modals/fileInterviewUpload" ></g:render>
	
</div>

